/* 用户信息管理页 类组件编程*/
import { Space, Form, Button, Select } from 'antd';
import { FormInstance } from 'antd/es/form';
import ExportJsonExcel from 'js-export-excel';

const { Option } = Select;

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
  labelAlign: 'left'
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};


import React, { Component } from 'react';
import {
  FcTable,
  FcButton,
  FcInput,
  FcMessage,
  FcModal,
  FcDivider,
  FcCard,
} from '@ngfed/fc-components';
import {
  getConditionSearch,
  getUserList,
  userDelete,
  userListAdd,
  userListUpdate,
} from './service';
import columnsData from './data';
import styles from './index.less';

class DataTable extends Component {
  formRef = React.createRef<FormInstance>();
  editformRef = React.createRef<FormInstance>();
  searchformRef = React.createRef<FormInstance>();


  state = {
    // 根据条件查询的列表数据
    datas: [],
    // 表头
    columns: [],
    // 删除提示框显示状态
    isModalVisible: false,
    //下载提示框显示状态
    isDownloadVisible: false,
    //下载链接
    downloadLink: '',
    // 删除信息Id和修改信息Id
    id: '',
    // 查询条件姓名
    name: '',
    // 用户添加模态框显示状态
    addModal: false,
    // 用户编辑模态框显示状态
    editModal: false,
    // 当前页码
    current: 1,
    // 每页显示数量
    pageSize: 5,

    selectedRowKeys: [], // Check here to configure the default column

    loading: false,


  };

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
    let arr = new Set(this.state.datas)
    let arr2 = new Set(this.state.selectedRowKeys)
    let arr3 = Array.from(arr.filter(value => {
      return arr2.has(value.seqNo)
    }))

    this.handleExportCurrentExcel(arr3)
  };


  onSelectChange = (selectedRowKeys: any) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  onFinish = (values: any) => {
    console.log(values);
    userListAdd(values).then(async (res: any) => {
      this.setState({ addModal: false });
      FcMessage.success(res.sysHead.retInf);
      (this as any).formRef.current.resetFields();
      this.getDatas()

    });
  };
  onFinishEdit = (values: any) => {
    console.log("sssaaadddssx" + this.state.id)
    console.log(values);
    userListUpdate(this.state.id, values).then(async (res: any) => {
      if (res.sysHead.retCd === '000000') {
        this.getDatas();
        this.setState({ editModal: false });
        FcMessage.success(res.sysHead.retInf);
        (this as any).editformRef.current.resetFields();

      }
    });
  };



  // 生命周期 数据初始化方法建议写在这个里面
  componentDidMount() {
    this.tableHeader();
    //不是错误
    this.getDatas();
  }

  // 表格头部数据重组
  tableHeader = () => {
    let columns: any = columnsData;
    const obj = {
      title: 'address',
      dataIndex: 'address',
      key: 'address',
      render: (text: any, record: any) => (
        <div>
          <a onClick={() => this.editUser(record)}>修改</a>
          <FcDivider type="vertical" />
          <a onClick={() => this.handleRemove(record.seqNo)}>删除</a>
        </div>
      ),
    };

    columns = [...columns, obj];
    this.setState({
      columns,
    });
  };

  /**
   * 数据查询
   * @param params 查询的参数对象
   */
  getDatas = () => {
    getUserList().then(async (res: any) => {
      console.log('res', res?.sysHead?.retCd);
      this.setState({
        datas: res.body,
      });
    });
  };
  //条件搜索
  getConditionSearch = (params: object) => {
    console.log(params)
    getConditionSearch(params).then(async (res: any) => {
      this.setState({
        datas: res.body,
      });
    });
  };
  // 重置
  reset = async () => {
    await this.setState({
      name: '',
    });
    await this.getDatas();
  };

  /**
   * 显示模态框提示是否删除
   * @param id 用户id
   */
  handleRemove = (id: string) => {
    this.setState({
      id,
      isModalVisible: true,
    });
  };

  // 确定删除用户数据
  handleOk = () => {
    userDelete({ seqNo: this.state.id }).then((res: any) => {

      if (res.sysHead.retCd === '000000') {
        this.getDatas();
        this.setState({ isModalVisible: false });
        FcMessage.success(res.sysHead.retInf);
      }
    });
  };

  // 添加
  addModalOk = async () => {
    try {
      // 非空验证
      const validate = await (this as any).addFormRef.current.validateFields();
      const param = await (this as any).addFormRef.current.getFieldsValue();

      userListAdd(param).then((res: any) => {
        if (res.sysHead.retCd === '000000') {
          this.getDatas();
          this.setState({ addModal: false });
          FcMessage.success(res.sysHead.retInf);
          // 重置表单
          (this as any).addFormRef.current.resetFields();
        }
      });
    } catch (err) {
      FcMessage.error('请输入必填项');
    }
  };

  /**
   * 编辑-点击打开模态框-回显
   * @param item 行对象数据
   */
  editUser = async (item: any) => {
    await this.setState({
      editModal: true,
      id: item.seqNo
    });
    // setTimeout(() => {
    //   (this as any).editFormRef.current.setFieldsValue(item);
    // }, 0);
  };

  // 保存编辑值-修改
  editUserOK = () => {
    const param = (this as any).editFormRef.current.getFieldsValue();
    console.log("修改++++++" + this.state.id)
  };

  /**
   * 表格分页
   * @param pageNum 当前页码
   * @param pageSize 每页显示数量
   */
  onChangeFn = (pageNum: number, pageSize: number) => {
    this.setState({
      current: pageNum,
      pageSize: pageSize,
    });
  };
  onReset = () => {
    this.searchformRef.current!.resetFields();
    this.getDatas()
  };

  handleExportCurrentExcel = (ExcelData: any) => { //ExcelData为后端返回的data数组
    let sheetFilter = ["seqNo", "type", "chineseName", "chineseNameAlias", "englishName", "englishNameShort", "meaning", "dataFormate", "scope", "codingRule", "reason"]
    let option = {};
    option.fileName = '原子服务接口表';
    option.datas = [
      {
        sheetData: ExcelData,
        sheetName: '原子服务接口表',
        sheetFilter: sheetFilter,
        sheetHeader: ['顺序号', '标准类型', '中文名称', '中文别名', '英文名称', '英文简称', '业务含义', '数据格式', '取值范围', '代码编码规则', '制定依据'],
        columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
      },
    ];

    var toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  }




  render() {

    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <div>
        {/* className 规范 */}
        {/* 单个class */}
        {/* <div  className={ styles.boxTitle }></div> */}
        {/* 多个class */}
        {/* <div  className={ `${styles.boxTitle} ${styles.boxText}` }></div> */}
        <div className={styles.box}>

          <Form {...layout} ref={this.searchformRef} name="control-ref" onFinish={this.getConditionSearch} labelAlign={'left'} layout="inline">
            <Space size={[8, 16]} wrap>

              <Form.Item label="标准类型" name="type" >
                <FcInput />
              </Form.Item>
              <Form.Item label="中文名称" name="chineseName" >
                <FcInput />
              </Form.Item>
              <Form.Item label="中文别名" name="chineseNameAlias" >
                <FcInput />
              </Form.Item>
              <Form.Item label="英文名称" name="englishName" >
                <FcInput />
              </Form.Item>
              <Form.Item label="英文简称" name="englishNameShort" >
                <FcInput />
              </Form.Item>
              <Form.Item label="业务含义" name="meaning" >
                <FcInput />
              </Form.Item>
              <Form.Item label="数据格式" name="dataFormate" >
                <FcInput />
              </Form.Item>
              <Form.Item label="取值范围" name="scope" >
                <FcInput />
              </Form.Item>
              <Form.Item label="代码编码规则" name="codingRule" >
                <FcInput />
              </Form.Item>
              <Form.Item label="制定依据" name="reason" >
                <FcInput />
              </Form.Item>
              <Form.Item style={{ marginRight: 8 }}
              >
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>

              <Button htmlType="button" onClick={this.onReset}>
                Reset
              </Button>
            </Space>
          </Form>
        </div>
<p></p>
        <FcCard
          title="用户信息"
          extra={
            <FcButton
              type="primary"
              onClick={() => {
                this.setState({ addModal: true });
              }}
            >
              {' '}
              +添加
            </FcButton>


          }
          bordered={false}
        >

          <div style={{ marginBottom: 16 }}>

            <FcTable rowKey="seqNo" rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.datas} />
          </div>
        </FcCard>

        <FcModal
          cancelText="取消"
          okText="确认"
          title="提示"
          visible={this.state.isModalVisible}
          onOk={this.handleOk}
          onCancel={() => {
            this.setState({ isModalVisible: false });
          }}
        >
          是否确定删除本条数据？
        </FcModal>

        <FcModal
          footer={null}
          destroyOnClose
          cancelText="取消"
          okText="新增"
          title="用户新增"
          visible={this.state.addModal}
          onOk={this.onFinish}
          onCancel={() => {
            this.setState({
              addModal: false,
            });
          }}
        >
          <Form {...layout} ref={this.formRef} name="control-ref" onFinish={this.onFinish} labelAlign={'left'}>
            <Form.Item label="标准类型" name="type" >
              <FcInput style={{ width: 100 }}
              />
            </Form.Item>
            <Form.Item label="中文名称" name="chineseName" >
              <FcInput />
            </Form.Item>
            <Form.Item label="中文别名" name="chineseNameAlias" >
              <FcInput />
            </Form.Item>
            <Form.Item label="英文名称" name="englishName" >
              <FcInput />
            </Form.Item>
            <Form.Item label="英文简称" name="englishNameShort" >
              <FcInput />
            </Form.Item>
            <Form.Item label="业务含义" name="meaning" >
              <FcInput />
            </Form.Item>
            <Form.Item label="数据格式" name="dataFormate" >
              <FcInput />
            </Form.Item>
            <Form.Item label="取值范围" name="scope" >
              <FcInput />
            </Form.Item>
            <Form.Item label="代码编码规则" name="codingRule" >
              <FcInput />
            </Form.Item>
            <Form.Item label="制定依据" name="reason" >
              <FcInput />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>

            </Form.Item>
          </Form>
        </FcModal>

        <FcModal
          footer={null}
          destroyOnClose
          cancelText="取消"
          okText="修改"
          title="用户编辑"
          visible={this.state.editModal}
          onOk={this.editUserOK}
          onCancel={() => {
            this.setState({ editModal: false });
          }}
        >
          <Form {...layout} ref={this.editformRef} name="control-ref" onFinish={this.onFinishEdit} labelAlign={'left'}>

            <Form.Item label="标准类型" name="type" >
              <FcInput style={{ width: 100 }}
              />
            </Form.Item>
            <Form.Item label="中文名称" name="chineseName" >
              <FcInput />
            </Form.Item>
            <Form.Item label="中文别名" name="chineseNameAlias" >
              <FcInput />
            </Form.Item>
            <Form.Item label="英文名称" name="englishName" >
              <FcInput />
            </Form.Item>
            <Form.Item label="英文简称" name="englishNameShort" >
              <FcInput />
            </Form.Item>
            <Form.Item label="业务含义" name="meaning" >
              <FcInput />
            </Form.Item>
            <Form.Item label="数据格式" name="dataFormate" >
              <FcInput />
            </Form.Item>
            <Form.Item label="取值范围" name="scope" >
              <FcInput />
            </Form.Item>
            <Form.Item label="代码编码规则" name="codingRule" >
              <FcInput />
            </Form.Item>
            <Form.Item label="制定依据" name="reason" >
              <FcInput />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>

            </Form.Item>
          </Form>
        </FcModal>

        <FcModal
          footer={null}
          destroyOnClose
          cancelText="取消"
          title="提示"
          visible={this.state.isDownloadVisible}
          onCancel={() => {
            this.setState({ isDownloadVisible: false });
          }}
        >

          <a href={this.state.downloadLink} target="_blank">点击下载</a>

        </FcModal>
      </div>
    );
  }
}

export default DataTable;
